package com.itheima.a03dom4jdemo;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class dom4jDemo2 {
    public static void main(String[] args) throws DocumentException {
        ArrayList<User> list = new ArrayList<>();

        //1.创建一个解析器对象
        SAXReader saxReader = new SAXReader();
        //2.对xml文件进行解析，并得到文档对象
        File file = new File("sockethomework\\src\\com\\itheima\\a03dom4jdemo\\users.xml");
        Document document = saxReader.read(file);
        //3.一层一层扒开得到xml文件里面的内容，先获得根标签
        Element rootElement = document.getRootElement();
        //4.获得根标签中的用户标签
        List<Element> elements = rootElement.elements();
        for (Element element : elements) {
            //属性id
            Attribute id = element.attribute("id");
            String idValue = id.getText();

            //用户名
            Element username = element.element("username");
            String usernameValue = username.getText();

            //密码
            Element password = element.element("password");
            String passwordValue = password.getText();

            //身份证
            Element personid = element.element("personid");
            String personidValue = personid.getText();

            //电话号码
            Element phoneid = element.element("phoneid");
            String phoneidValue = phoneid.getText();

            //是否是管理员
            Element flag = element.element("flag");
            String flagdValue = flag.getText();
            boolean b = Boolean.parseBoolean(flagdValue);

            //创建用户对象
            User user = new User(idValue, usernameValue, passwordValue, personidValue, phoneidValue, b);
            list.add(user);
        }
        //打印集合
        System.out.println(list);

        //登录操作
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入用户名：");
        String usernameInput = sc.nextLine();
        System.out.println("请输入密码：");
        String passwordInput = sc.nextLine();
        int index = getIndex(list, usernameInput);
        if (index >= 0) {
            //表示用户名存在，接下来判断密码
            if (list.get(index).getPassword().equals(passwordInput)){
                System.out.println("登录成功");
            }else {
                System.out.println("密码输入错误！");
            }
        } else {
            //表示用户名不存在
            System.out.println("用户名未注册！");
        }
    }

    //判断用户名是否存在
    public static int getIndex(ArrayList<User> list, String username) {
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).getUsername().equals(username)) {
                return i;
            }
        }
        //不存在返回-1
        return -1;
    }
}
